<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import DynamicForm from '@/components/form/DynamicForm.vue';
import { createDictionaryItemFormSchema, editDictionaryItemFormSchema } from '@/components/form/schemas/dictionaryItemFormSchema';
import type { Dictionary, DictionaryItem } from '@/api/endpoints/system/dictionary';
import { fetchDictionaryItemList, createDictionaryItem, updateDictionaryItem, deleteDictionaryItem } from '@/api/endpoints/system/dictionary';
import { toast } from '@/lib/toast';

interface Props {
  dictionary: Dictionary;
}

const props = defineProps<Props>();

const items = ref<DictionaryItem[]>([]);
const showCreateDialog = ref(false);
const showEditDialog = ref(false);
const editingItem = ref<DictionaryItem | null>(null);
const loading = ref(false);

onMounted(() => {
  loadItems();
});

async function loadItems() {
  try {
    const res = await fetchDictionaryItemList({ dictionaryId: props.dictionary.id });
    items.value = (res as any).data as DictionaryItem[];
  } catch (error) {
    console.error('加载字典项目失败:', error);
    toast.error('加载字典项目失败');
  }
}

// 创建字典项目
async function handleCreateItem(values: Record<string, any>) {
  loading.value = true;
  try {
    await createDictionaryItem(values as any);
    toast.success('字典项目创建成功');
    loadItems();
    showCreateDialog.value = false;
  } catch (error) {
    toast.error('字典项目创建失败');
    console.error('创建字典项目失败:', error);
  } finally {
    loading.value = false;
  }
}

// 编辑字典项目
async function handleEditItem(values: Record<string, any>) {
  if (!editingItem.value) {
    return;
  }

  loading.value = true;
  try {
    await updateDictionaryItem(editingItem.value.id, values);
    toast.success('字典项目更新成功');
    loadItems();
    showEditDialog.value = false;
    editingItem.value = null;
  } catch (error) {
    toast.error('字典项目更新失败');
    console.error('更新字典项目失败:', error);
  } finally {
    loading.value = false;
  }
}

// 删除字典项目
async function handleDeleteItem(item: DictionaryItem) {
  // if (!confirm(`确定要删除字典项目"${item.label}"吗？`)) {
  //   return;
  // }

  try {
    await deleteDictionaryItem(item.id);
    toast.success('字典项目删除成功');
    loadItems();
  } catch (error) {
    toast.error('字典项目删除失败');
    console.error('删除字典项目失败:', error);
  }
}

// 打开编辑对话框
function openEditDialog(item: DictionaryItem) {
  editingItem.value = item;
  showEditDialog.value = true;
}

// 关闭编辑对话框
function closeEditDialog() {
  editingItem.value = null;
  showEditDialog.value = false;
}
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 操作栏 -->
    <div class="p-4 border-b border-border">
      <div class="flex items-center justify-between">
        <div>
          <h3 class="text-lg font-semibold">
            {{ dictionary.name }}
          </h3>
          <p class="text-sm text-muted-foreground">
            字典项目管理
          </p>
        </div>
        <Dialog v-model:open="showCreateDialog">
          <DialogTrigger as-child>
            <Button size="sm">
              新建项目
            </Button>
          </DialogTrigger>
          <DialogContent class="max-w-2xl">
            <DialogHeader>
              <DialogTitle>新建字典项目</DialogTitle>
            </DialogHeader>
            <DynamicForm
              :schema="createDictionaryItemFormSchema"
              :initial-values="{ dictionaryId: dictionary.id }"
              :loading="loading"
              submit-button-text="创建"
              @submit="handleCreateItem"
              @cancel="showCreateDialog = false"
            />
          </DialogContent>
        </Dialog>
      </div>
    </div>

    <!-- 项目列表 -->
    <ScrollArea class="flex-1">
      <div class="p-4">
        <div v-if="items.length === 0" class="text-center py-8 text-muted-foreground">
          暂无字典项目
        </div>
        <div v-else class="grid gap-4">
          <Card
            v-for="item of items"
            :key="item.id"
            class="transition-colors hover:bg-muted/50"
          >
            <CardHeader class="p-4">
              <div class="flex items-center justify-between">
                <CardTitle class="text-base font-medium">
                  {{ item.label }}
                </CardTitle>
                <div class="flex items-center gap-2">
                  <Badge :variant="item.status === 1 ? 'default' : 'secondary'">
                    {{ item.status === 1 ? '启用' : '禁用' }}
                  </Badge>
                  <div class="flex gap-1">
                    <Button
                      size="sm"
                      variant="ghost"
                      @click="openEditDialog(item)"
                    >
                      编辑
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      @click="handleDeleteItem(item)"
                    >
                      删除
                    </Button>
                  </div>
                </div>
              </div>
            </CardHeader>
            <CardContent class="p-4 pt-0">
              <div class="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span class="text-muted-foreground">编码:</span>
                  <span class="ml-2">{{ item.code }}</span>
                </div>
                <div>
                  <span class="text-muted-foreground">值:</span>
                  <span class="ml-2">{{ item.value }}</span>
                </div>
                <div>
                  <span class="text-muted-foreground">排序:</span>
                  <span class="ml-2">{{ item.sort || 0 }}</span>
                </div>
                <div v-if="item.parentId">
                  <span class="text-muted-foreground">父级:</span>
                  <span class="ml-2">{{ item.parentId }}</span>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </ScrollArea>

    <Dialog v-model:open="showEditDialog">
      <DialogContent class="max-w-2xl">
        <DialogHeader>
          <DialogTitle>编辑字典项目</DialogTitle>
        </DialogHeader>
        <DynamicForm
          v-if="editingItem"
          :schema="editDictionaryItemFormSchema"
          :initial-values="editingItem"
          :loading="loading"
          submit-button-text="更新"
          @submit="handleEditItem"
          @cancel="closeEditDialog"
        />
      </DialogContent>
    </Dialog>
  </div>
</template>
